package com.weiquan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiquan.entity.ApiLogRecord;
import com.weiquan.mapper.ApiLogRecordMapper;
import com.weiquan.service.ApiLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * API日志服务实现类
 */
@Slf4j
@Service
public class ApiLogServiceImpl extends ServiceImpl<ApiLogRecordMapper, ApiLogRecord> implements ApiLogService {

    @Override
    public void saveApiLog(ApiLogRecord apiLogRecord) {
        try {
            this.save(apiLogRecord);
        } catch (Exception e) {
            log.error("保存API日志失败", e);
        }
    }

    @Override
    public Page<ApiLogRecord> getApiLogPage(int pageNum, int pageSize, String method, String status, String startTime, String endTime) {
        Page<ApiLogRecord> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ApiLogRecord> queryWrapper = new QueryWrapper<>();
        
        // 按请求方法筛选
        if (StringUtils.hasText(method)) {
            queryWrapper.eq("request_method", method);
        }
        
        // 按状态筛选
        if (StringUtils.hasText(status)) {
            queryWrapper.eq("status", status);
        }
        
        // 按时间范围筛选
        if (StringUtils.hasText(startTime)) {
            queryWrapper.ge("create_time", LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (StringUtils.hasText(endTime)) {
            queryWrapper.le("create_time", LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        return this.page(page, queryWrapper);
    }

    @Override
    public ApiLogRecord getApiLogById(Long id) {
        return this.getById(id);
    }

    @Override
    public void deleteExpiredLogs() {
        try {
            // 删除30天前的日志记录
            LocalDateTime expiredTime = LocalDateTime.now().minusDays(30);
            QueryWrapper<ApiLogRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.lt("create_time", expiredTime);
            
            int deletedCount = this.baseMapper.delete(queryWrapper);
            log.info("删除过期API日志记录 {} 条", deletedCount);
        } catch (Exception e) {
            log.error("删除过期API日志失败", e);
        }
    }

    @Override
    public Object getApiStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 今日请求总数
            LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            QueryWrapper<ApiLogRecord> todayWrapper = new QueryWrapper<>();
            todayWrapper.ge("create_time", todayStart);
            long todayCount = this.count(todayWrapper);
            statistics.put("todayCount", todayCount);
            
            // 今日成功请求数
            QueryWrapper<ApiLogRecord> todaySuccessWrapper = new QueryWrapper<>();
            todaySuccessWrapper.ge("create_time", todayStart)
                              .eq("status", "SUCCESS");
            long todaySuccessCount = this.count(todaySuccessWrapper);
            statistics.put("todaySuccessCount", todaySuccessCount);
            
            // 今日失败请求数
            QueryWrapper<ApiLogRecord> todayErrorWrapper = new QueryWrapper<>();
            todayErrorWrapper.ge("create_time", todayStart)
                            .eq("status", "ERROR");
            long todayErrorCount = this.count(todayErrorWrapper);
            statistics.put("todayErrorCount", todayErrorCount);
            
            // 平均响应时间（今日）
            Double avgResponseTime = this.baseMapper.getAvgResponseTime(todayStart);
            statistics.put("avgResponseTime", avgResponseTime != null ? avgResponseTime : 0.0);
            
            // 最常访问的接口（今日前5）
            statistics.put("topApis", this.baseMapper.getTopApis(todayStart, 5));
            
            // 请求方法分布
            statistics.put("methodDistribution", this.baseMapper.getMethodDistribution(todayStart));
            
            return statistics;
        } catch (Exception e) {
            log.error("获取API统计信息失败", e);
            return new HashMap<>();
        }
    }
}